package cn.wizzer.app.web.commons.doc;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PrintWord {
/*
    public static void main(String[] args) throws ZipException, TransformerConfigurationException, IOException, SAXException, ParserConfigurationException, TransformerException {
        modifyDocumentAndSave();
    }*/

    public static void modifyDocumentAndSave(String destFile,String destFile2,Map<String, String> bookMarkMap) throws IOException,ZipException, SAXException, ParserConfigurationException,TransformerException, TransformerConfigurationException {
        // 使用java.util打开文件
        File file = new File(destFile);
        boolean exist = file.exists();
        boolean read = file.canRead();
        boolean write = file.canWrite();
        /*System.out.println(exist);
        System.out.println(read);
        System.out.println(write);*/
        ZipFile docxFile = new ZipFile(file);
        // 返回ZipEntry应用程序接口
        ZipEntry documentXML = docxFile.getEntry("word/document.xml");

        InputStream documentXMLIS = docxFile.getInputStream(documentXML);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        Document doc = dbf.newDocumentBuilder().parse(documentXMLIS);


        /**
         * 书签列表
         */
        NodeList this_book_list = doc.getElementsByTagName("w:bookmarkStart");
        if (this_book_list.getLength() != 0) {
            for (int j = 0; j < this_book_list.getLength(); j++) {
                // 获取每个书签
                Element oldBookStart = (Element) this_book_list.item(j);
                // 书签名
                String bookMarkName = oldBookStart.getAttribute("w:name");
                // 书签名，跟需要替换的书签传入的map集合比较
                for (Map.Entry<String, String> entry : bookMarkMap.entrySet()) {
                    // 书签处值开始
                    int picType = getPicType(entry.getValue());
                    if(entry.getKey().equals(bookMarkName)) {
                        if (picType > 0 && file.exists()) {
                            FileInputStream fis = new FileInputStream(file);
                            BufferedImage bufferedImg = ImageIO.read(fis);
                            //addPicture(fis, picType, file.getName(), bufferedImg.getWidth(), bufferedImg.getHeight());
                        } else {
                            Node wr = doc.createElement("w:r");
                            Node wt = doc.createElement("w:t");
                            Node wt_text = doc.createTextNode(entry.getValue());
                            wt.appendChild(wt_text);
                            wr.appendChild(wt);
                            Element node = (Element) oldBookStart.getNextSibling();// 获取兄弟节点w:r
                            // 书签处值结束
                            // 如果书签处无文字,则在书签处添加需要替换的内容，如果书签处存在描述文字，则替换内容,用w:r
                            NodeList wtList = node.getElementsByTagName("w:t");// 获取w:r标签下的显示书签处内容标签w:t
                            if (wtList.getLength() == 0) { // 如果不存在，即，书签处本来就无内容，则添加需要替换的内容
                                oldBookStart.appendChild(wr);
                            } else { // 如果书签处有内容，则直接替换内容
                                Element wtNode = (Element) wtList.item(0);
                                wtNode.setTextContent(entry.getValue());
                            }

                        }
                    }
                }

            }
        }

        Transformer t = TransformerFactory.newInstance().newTransformer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        t.transform(new DOMSource(doc), new StreamResult(baos));
        ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFile2));
        Enumeration entriesIter = docxFile.entries();
        while (entriesIter.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entriesIter.nextElement();
            // 如果是document.xml则修改，别的文件直接拷贝，不改变word的样式
            if (entry.getName().equals("word/document.xml")) {
                byte[] data = baos.toByteArray();
                docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
                docxOutFile.write(data, 0, data.length);
                docxOutFile.closeEntry();
            } else {
                InputStream incoming = docxFile.getInputStream(entry);
                // 此处设定值需慎重，如果设置小了，会破坏word文档，至于为什么会破坏，自己去思考
                byte[] data = new byte[1024 * 512];
                int readCount = incoming.read(data, 0, (int) entry.getSize());
                docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
                docxOutFile.write(data, 0, readCount);
                docxOutFile.closeEntry();
            }
        }
        docxOutFile.close();
    }

    private static int getPicType(String bookmarkValue){
        int picType = -1;
        if(bookmarkValue.toLowerCase().contains(".emf")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_EMF;
        }else if(bookmarkValue.toLowerCase().contains(".wmf")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_WMF;
        }else if(bookmarkValue.toLowerCase().contains(".pict")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_PICT;
        }else if(bookmarkValue.toLowerCase().contains(".jpeg")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_JPEG;
        }else if(bookmarkValue.toLowerCase().contains(".png")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_PNG;
        }else if(bookmarkValue.toLowerCase().contains(".dib")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_DIB;
        }else if(bookmarkValue.toLowerCase().contains(".gif")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_GIF;
        }else if(bookmarkValue.toLowerCase().contains(".tiff")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_TIFF;
        }else if(bookmarkValue.toLowerCase().contains(".eps")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_EPS;
        }else if(bookmarkValue.toLowerCase().contains(".bmp")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_BMP;
        }else if(bookmarkValue.toLowerCase().contains(".wpg")){
            picType= org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_WPG;
        }
        return picType;
    }

}
